<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .box1{width:100px;height: 100px;background: red;position: absolute;left:0;top:0;}
    /* .box2{width:100px;height: 100px;background: red;position: absolute;left:0;top:0;} */
  </style>
</head>
<body>
  <div class="box1"></div>
  <!-- <div class="box2"></div> -->
</body>
<script>

  function Drag(ele){
    this.ele = ele;
    // 因为将来绑定事件时，要将方法直接作为事件处理函数使用
    // 所以要使用bind强行绑定this指向为当前类的实例
    // 又因为绑定事件和删除事件时需要找到同一个事件处理函数，而且bind每次执行会得到一个新函数
    // 所以，需要提前将bind改变this之后的新函数存起来，绑定和删除时才能找到同一个函数
    this.m = this.move.bind(this);
    this.u = this.up.bind(this);
    
    this.addEvent();
  }
  Drag.prototype.addEvent = function(){
    this.ele.addEventListener( "mousedown", this.down.bind(this) );
  }
  Drag.prototype.down = function(eve){
    this.downE = eve || window.event;
    
    document.addEventListener("mousemove", this.m );
    document.addEventListener("mouseup", this.u );
  }
  Drag.prototype.move = function(eve){
    this.moveE = eve || window.event;
    this.ele.style.left = this.moveE.pageX - this.downE.offsetX + "px";
    this.ele.style.top = this.moveE.pageY - this.downE.offsetY + "px";
  }
  Drag.prototype.up = function(){
    document.removeEventListener("mousemove", this.m );
    document.removeEventListener("mouseup", this.u );
  }

  const box1 = document.querySelector('.box1')
  new Drag(box1);
  
</script>
</html>